package com.base.dataStructure.stack;

import java.util.Iterator;

/**
 * @Author: hdhao
 * @Create: 2023/4/1 - 17:14
 * @Version: v1.0
 */
//基于数组实现栈结构(把数组的左边视为栈的底部,右边视为栈的顶部)
// 底            顶
// 0    1   2   3
@SuppressWarnings("all")
public class ArrayStack<E> implements Stack<E>,Iterable<E> {
    //底层数组
    private E[] array;
    //栈顶指针
    private int top;

    public ArrayStack(int capacity) {
        this.array = (E[]) new Object[capacity];
    }

    @Override
    public boolean push(E value) {
        if (isFull()){
            return false;
        }
        array[top] = value;
        top++;
        return true;
    }

    @Override
    public E pop() {
        if (isEmpty()){
            return null;
        }
        E topValue = array[top - 1];
        top--;
        return topValue;
    }

    @Override
    public E peek() {
        if (isEmpty()){
            return null;
        }
        E topValue = array[top - 1];
        return topValue;
    }

    @Override
    public boolean isEmpty() {
        return top == 0;
    }

    @Override
    public boolean isFull() {
        return top == array.length;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int p = top;
            @Override
            public boolean hasNext() {
                return p > 0;
            }

            @Override
            public E next() {
                E topValue = array[p - 1];
                p--;
                return topValue;
            }
        };
    }
}
